let express = require("express")(); 
let expressStatic = require("express-static"); 
const port = 80;
let mysql = require("mysql");
let bodyParser = require("body-parser");

express.use(bodyParser.json());
express.use(bodyParser.urlencoded({extended: false}));

let sql = mysql.createConnection({
	host     : 'localhost',
	user     : 'root',
	password : '123456',
	database : 'xm',
	timezone : "08:00"
});
sql.connect();

express.get("/find",function(request,response){
	sql.query(`SELECT * FROM detail`,function(error,data){
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send(data);
		}
	})
})

express.get("/getuser",function(request,response){
	sql.query(`SELECT * FROM user WHERE id=${request.query.id}`,function(error,data){
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send(data);
		}
	})
})

express.get("/detail",function(request,response){
	sql.query(`SELECT * FROM detail WHERE id=${request.query.id}`,function(error,data){
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send(data);
		}
	})
})

express.get("/pay",function(request,response){
	let p = request.query
	sql.query(`INSERT INTO shop (userID,goodsID,number,name,phoneNumber,province,city,area) VALUES ("${p.userID}","${p.goodsID}","${p.number}","${p.name}","${p.phoneNumber}","${p.province}","${p.city}","${p.area}")`,function(error,data){
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send("success");
		}
	})
})

express.get("/delete",function(request,response){
	sql.query(`DELETE FROM shop WHERE id=${request.query.id}`,function(error,data){
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send("success");
		}
	})
})

express.get("/select",function(request,response){
	sql.query(`SELECT shop.id,number,detail.img,name,phoneNumber,province,city,area,price,title from  shop,detail,user where shop.goodsID = detail.id AND userID = ${request.query.userID} AND user.id = ${request.query.userID}`,function(error,data){
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send(data);
		}
	})
})

express.post("/login",function(request,response){
	sql.query(`SELECT * FROM user WHERE username="${request.body.username}" AND password="${request.body.password}"`,(error,data)=>{
		if(error){
			response.send("error");
			console.log(error);
		}else{
			if(data.length === 0){
				response.send("error");
			}else{
				response.send(data);
			}
		}
	})
})

express.post("/register",function(request,response){
	sql.query(`INSERT INTO user (username,password) VALUES ("${request.body.username}","${request.body.password}")`,(error,data)=>{
		if(error){
			response.send("error");
			console.log(error);
		}else{
			response.send("success");
		}
	})
})

express.use(expressStatic(__dirname + '/static'));
console.log(`running at ${port}`)
express.listen(port)